#!/usr/bin/python env
# -*- coding: utf-8 -*-
from fabric.context_managers import lcd
from fabric.operations import local
from fabric.api import env, cd, sudo, run, put, settings, task, roles, execute
import time


env.roledefs = {
    'test': ['admin@172.16.0.8']
}
modules = {
    'registry': ['registry-center'],
    'adminlog': ['admin-system', 'log-service'],
    'service': ['api-gateway', 'user-service', 'task-service']
}
basePath = '/home/admin/app'
active='dev'


def build_project(branch='dev'):
    local('git checkout ' + branch)
    local('git pull')
    local('mvn clean package -Dmaven.test.skip=true')

def deploy_module(init=False, module=None):
    if module == None: return
    service = module.replace('-', '_')
    # mkdir
    if init:
        run('mkdir -p ' + basePath + '/config')
        put('config/deploy/' + active + '/public.yml', basePath + '/config/', mirror_local_mode=True)
        # service file
        put('config/deploy/service/' + service + '.service',
            '/etc/systemd/system/' + service + '.service',
            mirror_local_mode=True,
            use_sudo=True)
        # reload service
        sudo('systemctl enable /etc/systemd/system/' + service + '.service')
        sudo('systemctl daemon-reload')

    # config file
    put('config/deploy/' + active + '/' + module +  '.yml', basePath + '/config/', mirror_local_mode=True)
    put(module + '/target/' + module + '.jar', basePath, mirror_local_mode=True)
    sudo('chmod u+x /home/admin/app/' + module + '.jar')
    sudo('systemctl restart ' + service)


@roles('test')
def deploy_registry(init=False, build=False, branch='dev'):
    if build: build_project(branch)
    for module in modules.get('registry'):
        deploy_module(init, module)

@roles('test')
def deploy_adminlog(init=False, build=False, branch='dev'):
    if build: build_project(branch)
    for module in modules.get('adminlog'):
        deploy_module(init, module)

@roles('test')
def deploy_service(init=False, build=False, branch='dev'):
    if build: build_project(branch)
    for module in modules.get('service'):
        deploy_module(init, module)


def deploy(init=False, build=False, branch='dev'):
    if build: build_project(branch)
    execute(deploy_registry, init=init)
    print 'restart registry...'
    time.sleep(10)
    execute(deploy_adminlog, init=init)
    print 'restart admin and log...'
    time.sleep(10)
    execute(deploy_service, init=init)

